<?php

namespace app\api\controller;

use app\common\model\Activity;
use app\common\model\Banner;
use app\common\model\DrawRecord;
use app\common\model\Helpers;
use app\common\service\ChatService;
use think\Db;
use app\common\model\Users;

class Index extends Base
{


    public function _initialize()
    {
        parent::_initialize();
    }

    public function index()
    {
        dd(checkId());
        phpinfo();exit;
        $ip = request()->ip();
        echo 'api:';
        echo  $ip;exit('endTest');
    }



    /**
     * 获取banner及广告图
     */
    public function getBanner()
    {
        $model = new Banner();
        $where['status'] = 1;
        if (is_numeric(input('post.cid'))){
            $where['cid'] = input('post.cid');
        }
        $limit = is_numeric(input('post.num')) ? input('post.num') : 6;
        $rows = $model->getBanner($where,$limit);
        if (!empty($rows)) api_return(1, '获取成功', $rows);
        api_return(0, '暂无数据');
    }





    /**
     * 发送短信
     */
    public function sms()
    {
        if (request()->isPost()){
            $phone = input('post.phone');
            if (empty($phone)) api_return(0,'手机号码不能为空');
            $has = cache('code_num'.$phone);
            $endToday = strtotime(date('Y-m-d 23:59:59'));
            $time = $endToday - time();
            if ($has){
                if ($has['num'] >= 15)api_return(0,'短信发送过多');
                if ($has['time']+60 > time())api_return(0,'短信发送过于频繁,请一分钟后重试');
            }else{
                cache('code_num'.$phone,['num'=>0,'time'=>time()],$time);
            }
            $result = sendSms($phone);
            if ($result){
                cache('code_num'.$phone,['num'=>$has['num']+1,'time'=>time()],$time);
                api_return(1,'发送成功');
            }else{
                api_return(0,'发送失败');
            }
        }
        api_return(666,999);
    }


    public function test1()
    {
        $data['val1'] = '6398';
        $data['val2'] = '刺激战场';
        var_dump(sendCustomSms(18181366398,$data,'order'));
    }


    //生成微信分享二维码

    public function shareQrcode(){
        $data = request()->param('url');
        $res = code($data);
        api_return(1,'成功',$res);
    }

    public function test()
    {
//        $result = ChatService::getInstance()->wordfilter()->add('xiaosong');
//        dd($result);
        $sensitive = [
            'replace'=> '***',//敏感词替换，最长不超过 32 个字符， 敏感词屏蔽可以为空
            'keyword'=>"abc",//敏感词
            'type'=>0// 0: 敏感词替换 1: 敏感词屏蔽
        ];
//        $data = ChatService::getIns()->getSensitive()->add($sensitive);
//        dd($data);

        $result = ChatService::getIns()->getSensitive()->getList($sensitive);
        dd($result);
    }

    /**
     * 版本控制
     */
    public function version()
    {
        $new = Db::name('version')->field('versionCode,versionName,force,url,detail')->order('id desc')->cache(300)->find();
        if (!empty($new)) api_return(1,'获取成功',$new);
        api_return(0,'系统错误');
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 系统公告
     */
    public function notice()
    {
        $map['status'] = 1;
        $rows = Db::name('notice')->field('content')->where($map)->select();
        api_return(1,'获取成功',$rows);
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 随机获取推荐用户
     */
    public function users()
    {
        $map['status'] = 1;
        $users = Users::where($map)->orderRaw('rand()')->limit(12)->field('user_id,nick_name,header_img,sex')->select();
        api_return(1,'获取成功', $users);
    }

    /**
     * 获取大神协议
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    public function protocol()
    {
        $data = self::extend('protocol');
        api_return(1,'获取成功',$data);
    }
    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 获取最近热搜
     */
    public function hotField()
    {
        $data = self::getExplain('hot');
        $rows = explode(',',$data);
        api_return(1,'获取成功',$rows);
    }

    /**
     * 手气排行榜
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    public function RankingList()
    {
        $model = new DrawRecord();
        $map = [];
        if (input('time') == 'yesterday'){
            $time = 'yesterday';
        }else{
            $time = 'today';
        }


//        $map['a.price'] = ['>',520];
        $rows = $model->getRanks($map,$time);
        api_return(1,'获取成功',$rows);

    }
    
    /**
     * 获取扩展
     */
    public function explain()
    {
        $field = input('post.field');
        if (empty($field)) api_return(0,'参数不能为空');
        $rows = self::getExplain($field,true);

        api_return(1,'获取成功',$rows);
    }

    /**
     * 会员说明
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    public function vipView()
    {
        $data = self::extend('vip');
        api_return(1,'获取成功',$data);
    }

    /**
     * 获取公共聊天室信息
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    public function chatInfo()
    {
        $data = self::extend('chat_img,chat_name');
        $data['room_id'] = 'open_chat';
        api_return(1,'获取成功',$data);
    }

    /**
     * 获取融云token
     */
    public function token()
    {
        $token = $this->R_token($this->role_id);
        if ($token !== false) api_return(1,'获取成功',$token);
        api_return(0,'服务器繁忙,请稍后重试');
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 广场
     */
    public function square()
    {

        $data = input('post.');

        $user_id = self::getUserId();

        $map = [];

        if ($data['sex']){
            $map['a.sex'] = $data['sex'];
        }else{
            if ($user_id){
                $map['a.sex'] = $this->getSex($user_id);
            }
        }

        if ($data['section']){

            $time = ageDate($data['section']);
            $map['a.birthday'] = ['between time',$time];

        }

        if ($data['skill_id']){
            $map['s.skill_id'] = $data['skill_id'];
            $map['s.is_use'] = 1;
            $map['s.status']  = 1;
        }

        $model = new Users();

        $rows  = $model->rows($map,$user_id);

        api_return(1,'获取成功',$rows);

    }



    /**
     * 获取分类
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    public function skillList()
    {
        $model = new \app\common\model\Skill();
        $data['game'] = $model->getCateList(['type'=>2]);
        $data['fun']  = $model->getCateList(['type'=>1]);
        api_return(1,'获取成功',$data);
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 分类获取
     */
    public function cate()
    {
        $type = input('type');
        $model = new \app\common\model\Skill();

        $map = [];

        if (is_numeric($type)){
            $map['type'] = $type;
        }

        $rows = $model->getRows($map);

        api_return(1,'获取成功',$rows);

    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 分类详情
     */
    public function detail(int $id)
    {

        $map['skill_id'] = $id;
//        $map['status']   = 1;

        $model = new \app\common\model\Skill();

        $data  = $model->getDetail($map);

        api_return(1,'获取成功',$data);

    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 获取帮助文章
     */
    public function helpers()
    {
        $model = new Helpers();
        $rows  = $model->getRows(['status'=>1]);
        api_return(1,'获取成功',$rows);
    }




    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 融云在线状态改变
     */

    public function online_status()
    {
        $data = input();

        $appSecret = config('rongyun.appSecret');
        $nonce = $data['nonce'];
        $timestamp = $data['timestamp'];

        $signature = sha1($appSecret.$nonce.$timestamp);
        if ($signature == $data['signature']){
            $item = $data[0];
            $user_id = dehashid($item['userid']);

            if (!is_numeric($user_id))  exit('params error');
            $update['online_time'] = time();
//            $update['room_id'] = 0;

            $userExtra = self::userExtra('online_status,room_id',$user_id);

            if ($item['status'] === 0 || $item['status'] === '0'){ //上线

                if ($userExtra['online_status'] == 0){
                    $update['online_status'] = 1;

                    //用户上线发送消息至守护用户
//                    $str = sprintf('你守护的用户[%s]上线了!',$this->userInfo('nick_name',$user_id));
//                    $map['a.guard_user'] = $user_id;
//                    $map['a.end_time']   = ['>=',time()];
//                    $map['a.status']     = 1;
//                    $map['e.online_status'] = 1;
//                    Db::name('user_guard')->alias('a')->join('user_extend e','e.user_id = a.user_id')->where($map)->field('a.user_id')->chunk(1000,function ($users)use($str){
//                        $uid = [];
//                        foreach ($users as $user){
//                            $uid = hashid($user['user_id']);
//                        }
//                        self::sendUsrMsg('system',$uid,$str);
//                    });
                }

            }else{ //离线
//                $room_id = $userExtra['room_id'];
//                if ($room_id){
//                    $refresh = self::outRoomFunc($user_id,$room_id);
//                    if ($refresh){
//                        //需要刷新麦序
//                        $this->refreshWheat($room_id);
//                    }
//                }
                $update['online_status'] = 0;
            }
            self::updateUserExtend($user_id,$update);
            exit('success');
        }else{
            exit('params error');
        }
    }

    /**
     * 声网服务状态
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    public function voice_status()
    {
        $data = input('post.');
        $cache = cache('voice_status');

//        $data = $cache[3];

        $secret = 'ou8Wvbw0o';

//        $agoraSigntrue = request()->header('Agora-Signature');
////        $agoraSigntrue = 'b79b8d6b2d93c0346103c188eb2d37c1c6698646';
//
//        $json = json_encode($agoraSigntrue);
//
//        $sign = hash_hmac('sha1',$json,$secret);
////
//        if ($agoraSigntrue !== $sign){
//            api_return(0,'签名错误');
//        }

        if ($data['eventType'] == 104 || $data['eventType'] == 106){
            $user_id = Db::name('users')->where('uuid',$data['payload']['uid'])->cache(5)->value('user_id');
            if (!isInt($user_id)){
                api_return(0,'用户不存在');
            }

            $room_id = $data['payload']['channelName'];

            $refresh = self::outRoomFunc($user_id,$room_id);

            if ($refresh){
                $this->refreshWheat($room_id);

            }
            api_return(1,'成功');
        }


    }

    public function status()
    {
        dd(cache('voice_status'));
    }



    /**
     * 协议获取
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    public function agreement()
    {
        $rows = self::getExtend('user_text,privacy');
        api_return(1,'获取成功',$rows);
    }
    
    
    
    public function online_status1()
    {

        $data = input();

        $appSecret = config('rongyun.appSecret');
        $nonce = $data['nonce'];
        $timestamp = $data['timestamp'];

        $signature = sha1($appSecret.$nonce.$timestamp);

        if ($signature == $data['signature']){
            $item = $data[0];
            $user_id = dehashid($item['userid']);
            if (!is_numeric($user_id))  exit('params error');
            $update['online_time'] = time();
            if ($item['status'] == 1){
                $update['online_status'] = 1;
            }else{
                $room_id = self::staticExtra('room_id',$user_id);
                if ($room_id){
                    self::outRoomFunc($user_id,$room_id);
                }
                $update['room_id'] = 0;
            }
            self::updateUserExtend($user_id,$update);
            exit('success');
        }else{
            api_return(0,'参数错误');
        }
    }

    /**
     * 官网宣传页
     */
    public function web()
    {
        $rows = self::getExplain('companyName,url,IPC,companyAddress,ios,andriod,webKeywords,webDescription,webTitle');
        $this->assign([
            'rows' => $rows,
        ]);
        return view();
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 帮助文章
     */
    public function helper()
    {
        $id = input('id');
        $detail = Db::name('helpers')->where('h_id',$id)->cache(1)->find();
        $this->assign([
            'detail' => $detail,
        ]);
        return view();
    }

    /**
     * 活动列表
     */
    public function activity()
    {
        $rows = Activity::getActivity();
        api_return(1,'获取成功',$rows);
    }


}
